import 'package:x3_base_core/base_utils/base_utils.dart';
import 'package:x3_base_core/base_utils/base_transform_util.dart';
import 'package:x3_base_core/base_models/base_http_response_model.dart';
import 'package:x3_base_core/base_models/base_http_result_model.dart';

class BaseCatalogResponseModel {

  /// 构建组件数据
  List<BaseHttpResponseModel> response;

  /// 渲染组件源数据
  Map<String, dynamic> dataSource;

  BaseCatalogResponseModel(BaseHttpResultModel result) {
    var data = result.data;
    if (result.success == true) {
      this.response = data.containsKey('response') ? BaseTransformUtil.transformToListResponseData(data['response']) : <BaseHttpResponseModel>[];
      this.dataSource = data.containsKey('dataSource') ? data['dataSource'] : {};
    } else {
      this.response = <BaseHttpResponseModel>[];
      this.dataSource = {};
      BaseUtils.showToast('网络请求异常');
    }
  }

  /// 通过 appDisplay 筛选自定义组件的数据
  List<BaseHttpResponseModel> filterAppDisplay<T>(Iterable<T> enumValues) {
    return this.response.where((item) {
      dynamic value = BaseTransformUtil.enumFromString(enumValues, item.appDisplay);
      return value == null ? false : true;
    });
  }

  /// 获取 DataSource 数据
  dynamic findDataSource(String fieldName) {
    var data = this.dataSource.containsKey(fieldName) ? this.dataSource[fieldName] : null;
    if (data is List || data is String) {
      data = data.length == 0 ? null : data;
    }
    if (data is Map) {
      data = data.keys.length == 0 ? null : data;
    }
    return data;
  }

  @override
  String toString() {
    return 'BaseResponseDataModel{response: $response, dataSource: $dataSource}';
  }

}
